package com.example.tool.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.tool.entity.Dict;
import com.example.tool.exception.dict.DictIsNotExistException;
import com.example.tool.exception.dict.DictTypeIsExistException;
import com.example.tool.mapper.DictMapper;
import com.example.tool.service.DictService;
import com.example.tool.vo.DictReqVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class DictServiceImpl extends ServiceImpl<DictMapper,Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;
    @Override
    public List<Dict> list(){
        return dictMapper.selectList(Wrappers.emptyWrapper());
    }

    @Override
    public List<Dict> listByType(String type){
        return dictMapper.selectByType(type);
    }

    @Override
    public Page<Dict> selectPage(Integer page, Integer rows, DictReqVO dictReqVO) {
        return baseMapper.selectPage(
                Page.of(page,rows),
                Wrappers.lambdaQuery(Dict.class)
                        .eq(StringUtils.isNotEmpty(dictReqVO.getType()),Dict::getType,dictReqVO.getType())
                );
    }

    @Override
    public void add(Dict dict) throws DictTypeIsExistException {
        Dict tempDict = baseMapper.selectOne(
                Wrappers.lambdaQuery(Dict.class)
                        .eq(Dict::getType, dict.getType())
                        .eq(Dict::getName, dict.getName()));
        if (null!=tempDict){
            throw new DictTypeIsExistException();
        }
        baseMapper.insert(dict);
    }

    @Override
    public void delById(String id) throws DictIsNotExistException {
        Dict dict = baseMapper.selectOne(
                Wrappers.lambdaQuery(Dict.class)
                        .eq(Dict::getId, id)
        );
        if (null==dict){
            throw new DictIsNotExistException();
        }
        baseMapper.deleteById(dict);
    }

    @Override
    public void modify(Dict dict) throws DictTypeIsExistException {
        //查询数据库中的数据
        Long count = baseMapper.selectCount(
                Wrappers.lambdaQuery(Dict.class)
                        .eq(Dict::getType, dict.getType())
                        .eq(Dict::getName, dict.getName())
                        .ne(Dict::getId, dict.getId())
        );
        if (count>=1){
            throw new DictTypeIsExistException();
        }
        baseMapper.updateById(dict);
    }
}
